package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"os/exec"
	"runtime"
)

var wslPath *string

func main() {
	getWslPath()
	setReg()
	setWinsock()

	fmt.Println("修复完成,请重启计算机")
}

func setReg() {
	shell := "reg add "
	keyName := `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WinSock2\Parameters\AppId_Catalog\fix-wsl `
	fullPath := `/v AppFullPath /t REG_SZ /d ` + *wslPath + ` /f`
	lsp := `/v PermittedLspCategories /t REG_DWORD /d 1 /f`

	ExecShell(shell + keyName + fullPath)
	ExecShell(shell + keyName + lsp)
}

func setWinsock() {
	ExecShell("netsh winsock reset")
}

func getWslPath() {
	wslPath = flag.String("wsl_path", `C:\Windows\System32\wsl.exe`, "wsl.exe路径")
	flag.Parse()
}

func ExecShell(strCommand string) {
	var (
		name, arg string
		err       error
	)

	switch runtime.GOOS {
	case "linux":
		name, arg = "sh", "-c"
	case "windows":
		name, arg = "cmd", "/C"
	default:
		name, arg = "sh", "-c"
	}

	cmd := exec.Command(name, arg, strCommand)

	stdout, _ := cmd.StdoutPipe()
	if err = cmd.Start(); err != nil {
		handleErr(err, "Execute failed when Start", strCommand)
	}

	_, err = io.ReadAll(stdout)
	if err != nil {
		handleErr(err, "", "")
	}

	err = stdout.Close()
	if err != nil {
		handleErr(err, "", "")
	}

	if err = cmd.Wait(); err != nil {
		handleErr(err, "Execute failed when Wait", strCommand)
	}
}

func handleErr(err error, beforMsg, afterMsg string) {
	if err != nil {
		var errMsg string = err.Error()
		if beforMsg != "" {
			errMsg = beforMsg + ":" + errMsg
		}
		if afterMsg != "" {
			errMsg = errMsg + "----" + afterMsg
		}
		log.Fatal(errMsg)
	}
}
